package com.example.im.gray;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 *  定义服务间灰度调用规则
 */
@Component
public class GrayRule extends AbstractLoadBalancerRule {

    private static final String GRAY = "gray";
    private static final String GRAY_HEADER = "forward";
    private static final String GRAY_VALUE = "1";
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = getLoadBalancer();
        return this.choose(loadBalancer);
    }

    private Server choose(ILoadBalancer lb){
        Server server = null;
        if (server==null){
            Map<String, String> stringStringMap = GrayRibbonParamater.get();
            String grayParmater = null;
            if(stringStringMap!=null){
                grayParmater = stringStringMap.get("gray_header");
            }
            //获得可到达的服务
            List<Server> reachableServers = lb.getReachableServers();
            for (Server reachableServer : reachableServers) {
                //获取服务的metadata
                Map<String, String> metadata = ((DiscoveryEnabledServer) reachableServer).getInstanceInfo().getMetadata();
                if(StringUtils.equals(metadata.get(GRAY_HEADER),GRAY_VALUE)&&StringUtils.equals(grayParmater,GRAY)){
                    return reachableServer;
                }
            }
            if(server==null){
                logger.error("获取服务失败");
            }

        }
        return server;
    }

}
